package com.xxx.system.controller;


import com.github.pagehelper.PageInfo;
import com.xxx.base.utils.R;
import com.xxx.system.domain.Menu;
import com.xxx.system.query.MenuQuery;
import com.xxx.system.service.IMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//默认返回json格式，前后端分离
@RestController
@RequestMapping("/menu")
@Api(tags = "菜单接口类")
public class MenuController {
    @Autowired
    private IMenuService menuService;


    @GetMapping
    @ApiOperation(value = "查询所有菜单")
    public R<List<Menu>> findAll() {
        List<Menu> list = menuService.findAll();
        return R.ok(list);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "查询单个菜单")
    public R<Menu> findOne(@PathVariable("id") Long id) {
        Menu Menu = menuService.findOne(id);
        return R.ok(Menu);
    }

    @PutMapping
    @ApiOperation(value = "新增or修改菜单")
    public R<Void> addOrUpdate(@RequestBody Menu menu) {
        try {
            //获取请求参数的id
            Long id = menu.getId();
            if (id == null) {//新增没有传递id
                menuService.addMenu(menu);
            } else {
                menuService.updateMenu(menu);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("网络异常，请稍后重试!");
        }
        return R.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除单个菜单")
    public R<Void> deleteById(@PathVariable("id") Long id) {
        try {
            menuService.deteleById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("网络异常，请稍后重试!");
        }
        return R.ok();
    }

    @PostMapping
    @ApiOperation(value = "高级查询&分页")
    public R<PageInfo<Menu>> queryPage(@RequestBody MenuQuery menuQuery) {
        List<Menu> menuList = menuService.queryPage(menuQuery);
        //返回的是封装好的分页(总数,list)
        return R.ok(new PageInfo<Menu>(menuList));
    }

    @PatchMapping
    @ApiOperation(value = "批量删除")
    public R<Void> deleteMenuByIds(@RequestBody Long[] ids) {
        try {
            menuService.deleteMenuByIds(ids);
        } catch (Exception e) {
            e.printStackTrace();
            //返回的json格式  {"success":false,"message":"错误信息"}
            return R.fail("网络异常，请稍后重试!");
        }
        return R.ok();
    }

    @GetMapping("/menuTree/{id}")
    @ApiOperation(value = "获取父类型树")
    public List<Menu> getMenuTree(@PathVariable("id") Long id) {
        //获取部门树
        //Spring 缓存注解是基于Spring AOP切面，必须走代理才能生效，
        //同类调用或者子类调用父类带有缓存注解的方法时属于内部调用，没有走代理，所以注解不生效。
        List<Menu> list = menuService.findAll();
        return menuService.getMenuTree(list, id);
    }
}